package com.kqzz.common.exception;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.kqzz.common.api.response.Response;

/**
 * 无效token，resourceid不匹配异常处理，oauth模块独用
 */
@Component
public class MasterAuthExceptionEntryPoint implements AuthenticationEntryPoint {
	
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,AuthenticationException authException)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		Gson gson = new Gson();
		String result = "";
        Throwable cause = authException.getCause();
        
        if(!StringUtils.isBlank(request.getHeader("x-requested-with")) 
        		&& request.getHeader("x-requested-with").equals("XMLHttpRequest")){ // 判断客户端为ajax请求
        	response.setStatus(HttpStatus.OK.value());
        	response.setHeader("Content-Type", "application/json;charset=UTF-8");
        	// 进入此处异常后，前端应重定向到登录页面
        	try {
        		if(cause instanceof InvalidTokenException) {
        			result = gson.toJson(new Response().logout("token过期或帐号重复登录"));
        			response.getWriter().write(result);
        		}else if(cause instanceof OAuth2AccessDeniedException){ // 对resourceid不匹配的请求拒绝
        			result = gson.toJson(new Response().failure("无权限访问当前资源"));
        			response.getWriter().write(result);
        		}else if(null==cause && authException instanceof InsufficientAuthenticationException){
        			result = gson.toJson(new Response().logout("token不存在,检查Authorization属性"));
        			response.getWriter().write(result);
        		}
        	} catch (IOException e) {
        		e.printStackTrace();
        	}
        }else{
    		request.setAttribute("msg", "登录失败，请核对后登录");
    		
//        		String savedRequestUrl = Base64.decodeStr(request.getParameter("callbackurl"));
    		request.setAttribute("callbackurl", request.getParameter("callbackurl"));
    		request.getRequestDispatcher("/returnLogin").forward(request, response);
        }
    }
}
